<?php

namespace app\index\controller;

use app\index\model\Cart;
use app\index\model\Pictures;
use think\Controller;

class CartCtl extends Controller
{
    /*
     * 加入购物车
     */
    public function addCart()
    {
        if (($cart = Cart::where(['uid' => input('uid'), 'spu_id' => input('spu_id')])->find()) != null) {
            $cart->amount += input('amount');
            $cart->save();
        } else {
            Cart::create([
                'uid' => input('uid'),
                'amount' => input('amount'),
                'spu_id' => input('spu_id')
            ]);
        }
        return json(['msg' => '添加成功！', 'code' => 20000]);
    }

    /*
     * 删除购物车商品
     */
    public function delCart()
    {
        if (input(('?get.id'))) {
            Cart::destroy(input('id'));
        }
        if (input('?get.uid')) {
            Cart::where('uid', input('uid'))->delete();
        }
        return json(['msg' => '删除成功！', 'code' => 20000]);
    }

    /*
     * 获取用户购物车内容
     */
    public function getCartByUid()
    {
        $goods = Cart::where('uid', input('uid'))->with('spu,spu.goods')->select();
        foreach ($goods as $g) {
            //
            $g['sku'] = setOrderSku($g['spu']['id']);
            $g['picture'] = Pictures::where(['gid' => $g['spu']['gid'], 'type' => 0])->value('url');
        }
        $res['data'] = $goods;
        $res['code'] = 20000;
        return json($res);
    }

    /*
     * 更新购物车商品的数量
     */
    public function updCart()
    {
        $goods = json_decode(stripslashes(html_entity_decode(input('goods'))), true);
        $cart = new Cart;
        $cart->saveAll($goods);
        return json(['msg' => '更新成功！', 'code' => 20000]);
    }
}